package com.zky.service;

import com.zky.mapper.UserMapper;
import com.zky.pojo.User;
import com.zky.util.JwtHelper;
import com.zky.util.MD5Util;
import com.zky.util.Result;
import com.zky.util.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class userServiceImp implements userService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public Result login(User user) {
        User user1 = userMapper.selectUserByName(user.getUsername());
        if(user1==null){
            return Result.build(null, ResultCodeEnum.USERNAME_ERROR);
        }
        else
        {
            if(user.getUserPwd()!=null&&user1.getUserPwd().equals(MD5Util.encrypt(user.getUserPwd())))
            {
                String token = jwtHelper.createToken(Long.valueOf(user1.getUid()));

                Map data = new HashMap();
                data.put("token",token);

                return Result.ok(data);
            }
            return Result.build(null,ResultCodeEnum.PASSWORD_ERROR);
        }
    }

    @Override
    public Result getUserInfo(String token) {
        //判定是否在有限期
        if(jwtHelper.isExpiration(token))
        {
            return Result.build(null,ResultCodeEnum.NOTLOGIN);
        }
        int userId = jwtHelper.getUserId(token).intValue();
        User user = userMapper.selectUserById(userId);
        if (user != null) {
            user.setUserPwd(null);
            Map data = new HashMap();
            data.put("loginUser",user);
            return Result.ok(data);
        }

        return Result.build(null,ResultCodeEnum.NOTLOGIN);

    }

    @Override
    public User selectUserById(int id) {
        User user = userMapper.selectUserById(id);
        return user;
    }
    @Override
    public Result checkUserName(String username) {
        User user = userMapper.selectUserByName(username);
        if (user != null){
            return Result.build(null,ResultCodeEnum.USERNAME_USED);
        }
        return Result.ok(null);
    }

    @Override
    public Result regist(User user) {
        if(userMapper.selectUserByName(user.getUsername())!=null)
        {
            return Result.build(null,ResultCodeEnum.USERNAME_USED);
        }
        user.setUserPwd(MD5Util.encrypt(user.getUserPwd()));
        int rows = userMapper.insert(user);
        System.out.println("rows = " + rows);
        return Result.ok(null);

    }
}
